import titleBar from '@/components/title_bar/index.vue'
import amap from './amap/index.vue'
import {defaultCityList} from './constant.js'
import {id} from '@/utils/_'
import {inputAbsolute} from '@/utils/ios'
import {isPhone} from '@/utils'
import {SERVEAMAPKEY} from '@/utils/amap.js'
import axios from 'axios'
let vm = null
export default {
    components: {
        titleBar,
        amap,
    },
    data(){
        return {
            realName: '',
            phone: '',
            addressBak: '',
            openCity: false,
            originCityList: [],
            cityList: defaultCityList,
            cityPick: void 0,
            citySelected: '',
            city2ColumnIndex: 0,
            position: {},
            nearestJunction: '',
            // 加载成功数据
            isLoadMap: false,
            // 加载的ct
            citysResponse: [],
            // 是否编辑
            isEdit: false,
            addressId: -1,
            // 编辑状态下获取的位置 [lng, lat]
            oldPosition: [],
            // 设置城市的名称
            setCityName: '',
            // 已选择的POI
            pickPOI: {},
            POI: [],
            showPOI: false,
            posStyle: {},
            setCenterSite: false,
            inputAbsolute: inputAbsolute(),
            showBottom: true,
            run: false,
            // search
            isSearchPOI: false,
            showSearchPOI: false,
            searchPOIS: [],
            isNeedPrevent: false,
            showSearchClose: false,
            searchResultPosStyle: {},
            city: '',
			innerHeights:[]
        }
    },
    created(){
        vm = this
        this.run = false
        let isEdit = Boolean(this.$route.query.edit)
        let addressId = this.$route.query.id
        this.$toast.loading({
            duration: 0,
            mask: true,
            loadingType: 'spinner',
            // message: ''
        })
        this.initCity(isEdit ? async () => {
            console.log('--编辑状态 拉取初始化信息中--')
            console.log(addressId)
            let addressResponse = await HTTP('app/userAddress/addressDetailByUid', {
                addressUid: addressId,
            })
            try {
                if(addressResponse.code !== 200){
                    this.$toast( addressResponse.msg|| '服务器开小差了')
                    return
                }
                console.log('---addressResponse--')
                console.log(addressResponse.data)
                this.realName = addressResponse.data.userName
                this.phone = addressResponse.data.phone
                this.nearestJunction = addressResponse.data.address
                this.addressBak = addressResponse.data.addressInfo
                this.oldPosition = [+addressResponse.data.longitude, +addressResponse.data.latitude]
                // 打开地图
                this.isLoadMap = true
            } catch (error) {
                this.$toast('数据开小差了')
                console.log(error)
            }
        } : () => {
            this.isLoadMap = true
        })
        this.isEdit = isEdit
        this.addressId = addressId
    },
    mounted(){
		window.addEventListener('resize', this.handleSize.bind(this), false)
        let rect = this.$refs.showsite.getBoundingClientRect()
        let top = rect.top + rect.height - 2 // (2是圆角)
        console.log(rect)
        // console.log(this.$refs.showsite)
        this.posStyle = {
            top: top + 'px',
            height: `calc(100vh - ${top}px)`
        }
    },
	destroyed(){
		window.removeEventListener('resize', this.handleSize, false)
	},
    methods: {
		handleSize(){
			console.log(111)
			this.innerHeights.push(window.innerHeight)
            this.innerHeights = this.innerHeights.filter( (item, index ,arr)=>arr.indexOf(item) === index )
            let maxValue = Math.max(...this.innerHeights)
            let minValue = Math.min(...this.innerHeights)
            let open = () => {
                console.log('键盘出来')
            }
            let close = () => {
                console.log('键盘关闭')
                this.blur()
            }
            if(this.innerHeights.length == 1){
                open()
                return
            }
            if(window.innerHeight === maxValue){
                close()
            }
            if(window.innerHeight === minValue){
                open()
            }
		},
        async initCity(successCallBack){
            try {
                // 获取深圳城市区域列表
                const citysResponse = await HTTP('order/selectArea', {
                    cityUid: 202
                })
                let getCityList = (e) => {
                    return {
                        name: e.areaName,
                        site: [e.longitude,  e.latitude]
                    }
                }
                if(citysResponse.code !== 200){
                    this.$toast('服务器开小差了')
                    return
                }
                console.log('---citysResponse--')
                console.log(citysResponse)
                this.citysResponse = citysResponse.data
                this.originCityList = citysResponse.data.map(getCityList)
                console.log('this.originCityList')
                console.log(this.originCityList)
                this.$toast.clear()
                successCallBack && successCallBack()
            }catch(e){
                this.$toast.clear()
                this.$toast('服务器开小差了')
                console.log(e)
            }
        },
        // TODO 添加锁
        async success(){
            console.log('修改中')
            if(this.run){
                console.log('---锁---')
                return
            }
            // TODO 校验 
            let site = this.citysResponse.find(e => e.areaName.replace('新', '') === this.citySelected)
            let params = {
                userUid: getuserUid(),
                userName: this.realName,
                phone: this.phone,
                address: this.nearestJunction,
                addressInfo: this.addressBak,
                cityUid: 202,
                provinceUid: 19,
                longitude: this.position?.lng,
                latitude: this.position?.lat,
                areaUid: site.areaUid,
                createBy: getuserUid(),
                addressType: 2,
            }
            // console.log(params)
            if(!this.realName){
                this.$toast('请输入名字')
                return
            }
            if(!this.phone){
                this.$toast('请输入手机号')
                return
            }
            if(!isPhone(this.phone)){
                this.$toast('请输入正确的手机号')
                return
            }
            if(!this.addressBak){
                this.$toast('请输入地址备注')
                return
            }
            try{
				this.run = true
                let response
                if(this.isEdit){
                    response = await HTTP('app/userAddress/updateAddress', {
                        ...params,
                        uid: this.addressId,
                        addressType: 2,
                        updateBy: params.createBy,
                    })
                }else{
                    response = await HTTP('app/userAddress/addAddress', params)
                }
                if(response.code !== 200){
                    this.$toast(response.msg || '服务器开小差了')
                    this.run = false
                    return
                }
                this.$toast('地址添加成功')
                setTimeout(() => {
                    this.$router.go(-1)
                    this.run = false
                }, 5e2);
                console.log(response)
            }catch(e){
                this.$toast('服务器开小差了')
                console.log(e)
                this.run = false
            }
        },
        cityChange(picker, values){
            // console.log(picker, values)
            // console.log(values)
            this.cityPick = values
            this.city2ColumnIndex = picker.getColumnIndex(1)
        },
        onopenCity(){
            this.openCity = true
            setTimeout(() => {
                this.$refs.ct.setColumnIndex(1, this.city2ColumnIndex)
            }, 200)
        },
        cityDone(){
            this.openCity = false
            if(!this.cityPick){
                // console.log(this.cityList)
                this.cityPick = [
                    this.cityList[0].values[0],
                    this.cityList[1].values[0]
                ]
            }
            this.citySelected = this.cityPick[1]
            // 推送到子组件
            this.setCityName =  this.cityPick[1]
        },
        // 地图显示的实时位置
        mapCB(positionResult){
            console.log('回调')
            console.log(positionResult, this.position)
            vm.city = positionResult.regeocode.addressComponent.city
            console.log(positionResult.regeocode.addressComponent.city)
            vm.getCityCallback(positionResult.regeocode.addressComponent)
            // this.position = positionResult.position
            // this.nearestJunction = positionResult.nearestJunction
            if(vm.position && positionResult.position.lng === vm.position.lng && positionResult.position.lat === vm.position.lat){
                return
            }
            vm.setPOI(positionResult.regeocode.pois[0])
            vm.POI = positionResult.regeocode.pois
        },
        // 默认定位的位置
        getCityCallback(city){
            console.log('设置默认定位位置', city.district)
            let run = () => {
                try {
                    console.log('citySelected', this.citySelected)
                    let districtIndex  = this.cityList[1].values.findIndex(e => e === city.district)
                    this.city2ColumnIndex = districtIndex
                    this.citySelected = city.district   
                    setTimeout(() => {
                        console.log('citySelected test', this.citySelected)
                    }, 5e3);
                } catch (error) {
                    console.log('设置约定地点error')
                    console.log(error)
                }
            }
            ;[0, 500].forEach(e => {
                setTimeout(() => {
                    run()
                }, e)
            })
        },
        onShowPOI(){
            this.showPOI =! this.showPOI
        },
        onSetPOI(poi){
            vm.setPOI(poi)
            vm.setCenterSite = [poi.location.lng, poi.location.lat]
            this.$refs.searchPOIInput.value = ''
        },
        setPOI(poi){
            // console.log(this)
            // console.log(this.data)
            // console.log('set poi')
            // console.log(poi)
            // this.position = poi.location// regeocode
            // this.nearestJunction = poi.name
            // this.pickPOI = poi
            // this.showPOI = false
            
            vm.position = poi.location// regeocode
            vm.nearestJunction = poi.name
            vm.pickPOI = poi
            vm.showPOI = false
            vm.showSearchPOI = false
            vm.isSearchPOI = false
        },
        focus(){
            this.showBottom = false
        },
        blur(){
            let run = () => {
                this.showBottom = true
            }
            ;[0, 50, 100, 500].forEach(e => {
                setTimeout(() => {
                    this.showBottom = true
                }, e)
            })
        },
        phoneNumberInput(e){
            // console.log(e)
            // console.log(this.phone)
            this.phone = this.phone.replace(/[^\d]/g, '').substr(0, 11)
        },
        onSearchPOI(){
            this.isSearchPOI = true
            let foucsInput = () => {
                this.$refs.searchPOIInput.focus()
            }
            ;[300].forEach(e => {
                setTimeout(() => {
                    foucsInput()
                }, e)
            })
            if(JSON.stringify(this.searchResultPosStyle).length <= 2){
                let run = () => {
                    let rect = this.$refs.searchSite.getBoundingClientRect()
                    let top = rect.top + rect.height - 2
                    this.searchResultPosStyle = {
                        top: top + 'px',
                        height: `calc(100vh - ${top}px)`
                    }
                    this.$refs.searchPOIInput.addEventListener('compositionstart', () => {
                        this.isNeedPrevent = true
                    })
                    this.$refs.searchPOIInput.addEventListener('compositionend', (e) => {
                        this.isNeedPrevent = false
                        this.handleSearchPOI(e)
                    })
                }
                ;[300].forEach(e => {
                    setTimeout(() => {
                        run()
                    }, e)
                })
            }
        },
        searchChagnge(e){
            var flag = this.isNeedPrevent;
            if(flag){
                return
            }
            this.handleSearchPOI(e)
        },
        handleSearchPOI(e){
            // console.log(vm.pickPOI)
            // console.log(this.city)
            let value = e.target.value
            this.showSearchClose = false
            if(!this.city){
                console.log('未获取到城市')
                return
            }
            if(value.replace(/\s/g, '') === ''){
                vm.searchPOIS = []
                vm.showSearchPOI = false
                return
            }
            this.showSearchClose = true
            // axios.post('/app/buser/resetMsg', {
            //     params: {
            //         key: AMAPKEY,
            //         keywords: value,
            //     }
            let URL = `https://restapi.amap.com/v3/place/text?key=${SERVEAMAPKEY}&city=${this.city}&keywords=${value}`
            HTTP('app/buser/resetMsg', {
                url: URL
            }).then(result => {
                if(result.code !== 200){
                    this.$toast('服务器开小差了')
                    console.log('---异常---')
                    return
                }
                let response = JSON.parse(result.data)
                console.log(response)
                if(response.status != 1){
                    this.$toast('异常')
                    return
                }
                this.searchPOIS = response.pois.map(e => {
                    let lng = +e.location.split(',')[0]
                    let lat = +e.location.split(',')[1]
                    let location = {
                        lng,
                        lat,
                        Q: lng,
                        p: lat,
                    }
                    return {...e,
                        location,
                    }
                })
                console.log('search:', value)
                this.showSearchPOI = true
            }).catch(e => {
                this.$toast('服务器开小差了')
            })
        },
        onCloseSearch(){
            vm.showSearchPOI = false
            vm.isSearchPOI = false
            vm.searchPOIS = []
            vm.showSearchClose = false
        },
        onSearchCloseButton(){
            vm.showSearchClose = false
            this.$refs.searchPOIInput.value = ''
            // this.handleSearchPOI({target: this.$refs.searchPOIInput})
            this.onCloseSearch()
            this.blur()
        },
    }
}